/**
 * @author 铭
 * @TODO 9/1/2024
 */
package com.woniuxy.service.impl;

import com.woniuxy.daos.TbCustomerDao;
import com.woniuxy.entitys.TbCustomer;
import com.woniuxy.entitys.TbCustomerExample;
import com.woniuxy.service.CustomerLoginService;
import com.woniuxy.utils.JWTUtils;
import com.woniuxy.utils.LoginCustomer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import java.util.List;

@Service
public class CustomerLoginServiceImpl implements CustomerLoginService {
    @Resource
    private TbCustomerDao tbCustomerDao;
    @Autowired
    private JWTUtils jwtUtils;
    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public TbCustomer login(TbCustomer customer) {
        TbCustomerExample tbCustomerExample = new TbCustomerExample();
        TbCustomerExample.Criteria criteria = tbCustomerExample.createCriteria();
        criteria.andPhoneEqualTo(customer.getPhone());
        criteria.andPasswordEqualTo(customer.getPassword());

        List<TbCustomer> tbCustomers = tbCustomerDao.selectByExample(tbCustomerExample);
        if (tbCustomers.size()!=0){
            return tbCustomers.get(0);

        }
        return null;

    }

    @Override
    public void deleteToken(String token) {
        String username = jwtUtils.getUsername(token);
        redisTemplate.delete("customer:"+username);
    }
    @Override
    public int cupdPwd(String oldPwd, String newPwd) {
        ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        String header = servletRequestAttributes.getRequest().getHeader("token");
        String username = jwtUtils.getUsername(header);
        ValueOperations valueOperations = redisTemplate.opsForValue();
        LoginCustomer loginUser = (LoginCustomer) valueOperations.get("customer:" + username);

        TbCustomer customer = loginUser.getCustomer();
        if (!customer.getPassword().equals(oldPwd)){
            return 0;
        }
        customer.setPassword(newPwd);

        return tbCustomerDao.updateByPrimaryKeySelective(customer);
    }
}
